import { forwardRef, useContext, useImperativeHandle, useRef, useState } from 'react';

import { msgError } from '@/utils/msg';
import { getDevOption } from '@/utils/pub';
import { Button } from 'devextreme-react';
import { IColumnProps } from 'devextreme-react/data-grid';
import { DevGrid, DevPopup } from '~/public/cpas-ui';
import { LayoutD } from '~/public/cpas-ui/components-bs/Layout';
import { consts } from '../../consts';
import { OverallMode, ProjectOverallProps, SampleStepInfo, SampleTable } from '../../typing';
import '../index.less';
import SamplingProjectOverall from '../samplingProjectOverall';
import { SampleStepInfoContext } from '../samplingRecordPopup';
import { getSampleSourceColumsOfExists } from '../samplingSourceService';
import { devPopupTitleRendered, getDeleteGridSelectRows } from '../service';
import { leftVerticalDivStyle } from './NonStatSampleService';

/**
 * 统计抽样
 */
export const ViewSampleListPopup = forwardRef((prop, ref) => {
  const sampleStepInfo: SampleStepInfo = useContext(SampleStepInfoContext);
  const curSampleTable: SampleTable = sampleStepInfo.projectOverallProps?.curSampleTable as any;

  if (!curSampleTable?.tableName) return;

  const [visible, setVisible] = useState<boolean>(false);

  const [focusedRowIndex, setFocusedRowIndex] = useState<number>(0);
  const diaParams = useRef<any>();
  const dataGridRef = useRef<any>();
  const [sampleProjectOverallProps, setSampleProjectOverallProps] = useState<ProjectOverallProps>();

  const [selectGridColumns, setSelectGridColumns] = useState<IColumnProps[]>([]);
  const [gridRowsData, setGridRowsData] = useState<any[]>([]);
  const [toolbarVisible, setToolbarVisible] = useState<boolean>(true);
  const [confirmDelete, setConfirmDelete] = useState<boolean>(true);
  //抽样总体引用
  const samplingProjectOverallRef = useRef<any>(null);
  useImperativeHandle(ref, () => ({
    show: (params: any) => {
      //{title,whereSql,setIsNeedViewSampleListPopup,specialSampleList}
      diaParams.current = params;
      setVisible(true);
      setToolbarVisible(params.sampleProjectOverallProps.overallMode == OverallMode.select);
      setTimeout(() => {
        if (params.sampleProjectOverallProps.overallMode == OverallMode.select) {
          const sampleTable = params.sampleProjectOverallProps.curSampleTable;
          const sampleSourceFields = sampleTable.sampleAllFieldsArray; // await getSampleSourceFields(dbname, sampleTable.tableName);
          const columns: IColumnProps[] = getSampleSourceColumsOfExists(
            sampleTable,
            sampleSourceFields,
            true,
          );
          columns.push({
            caption: '操作',
            type: 'buttons',
            fixed: true,
            fixedPosition: 'left',
          });
          setSelectGridColumns(columns);
          setGridRowsData(params.specialSampleList);
        }

        setSampleProjectOverallProps(params.sampleProjectOverallProps);
      }, 400);
    },
  }));

  function onCancel() {
    setVisible(false);
    diaParams.current?.setIsNeedViewSampleListPopup(false);
  }
  let title = !diaParams.current?.title ? '查看样本' : `${diaParams.current?.title}`;

  return (
    <>
      <DevPopup.Logic
        visible={visible}
        title={title}
        width="90vw"
        height="90vh"
        onHiding={onCancel}
        onCancel={onCancel}
        onTitleRendered={(e) => {
          devPopupTitleRendered(e, '500px');
        }} //解决 dx-popup 标题有....的问题
        onOK={() => {
          /* if (gridRowsData.length) {
                    diaParams.current?.okCallback(gridRowsData)
                    diaParams.current?.setIsNeedViewSampleListPopup(false)
                } else {
                    msgError('请选择数据特殊样本!')
                } */

          diaParams.current?.okCallback(gridRowsData);
          diaParams.current?.setIsNeedViewSampleListPopup(false);
        }}
        toolbarDisplay={toolbarVisible}
      >
        {() => {
          //必须用函数返回

          function topContainer() {
            //手工增加事件
            function doManualAddSample(
              sampleProjectOverallProps: ProjectOverallProps,
              rowData: any,
            ) {
              const sampleTextFieldsArray: string[] =
                sampleProjectOverallProps.curSampleTable?.sampleTextFieldsArray || [];

              const curGridRowsData: any[] = getDevOption(dataGridRef, 'dataSource') || [];

              let values1 = '';
              sampleTextFieldsArray.forEach((fieldName) => {
                values1 += `${rowData[fieldName]}`;
              });

              const findIndex = curGridRowsData.findIndex((item2) => {
                let values2 = '';
                sampleTextFieldsArray.forEach((fieldName) => {
                  values2 += `${item2[fieldName]}`;
                });
                return values1 == values2;
              });
              if (findIndex == -1) {
                curGridRowsData.push({ ...rowData });
                curGridRowsData.forEach((item, index) => (item.rn = index + 1));

                setGridRowsData([...curGridRowsData]);
                // setDevOptions(dataGridRef, { dataSource: findIndex })
              } else {
                dataGridRef.current.instance.getScrollable().scrollTo({ top: findIndex });
                setFocusedRowIndex(findIndex);
                msgError(`此行数据已经存在!`);
              }
            }
            if (sampleProjectOverallProps) {
              sampleProjectOverallProps.exportFileNameOnly = title;
              sampleProjectOverallProps.events = {
                onLoadData: (retData: { rowsData: any[]; totalCount: number }) => {
                  //setTotalCount(retData.totalCount)
                },
                onRowDblClick: (e) => {
                  doManualAddSample(sampleProjectOverallProps, e.data);
                },
                onManualAddSample: (e) => {
                  doManualAddSample(sampleProjectOverallProps, e.row.data);
                },
              };
            }
            return (
              sampleProjectOverallProps && (
                <SamplingProjectOverall
                  ref={samplingProjectOverallRef}
                  propsOfParams={sampleProjectOverallProps}
                />
              )
            );
          }
          function bottomContainer() {
            return (
              sampleProjectOverallProps && (
                <div
                  className="itemBoxDispalyLeft"
                  style={{
                    marginTop: 5,
                    marginLeft: 0,
                    height: '90%',
                    border: '1px solid #e5e5e5',
                    borderRadius: 5,
                    width: '100%',
                  }}
                >
                  <div style={{ ...leftVerticalDivStyle, paddingTop: 20 }}>
                    <div>已</div>
                    <div>选</div>
                    <div>样</div>
                    <div>本</div>
                    <div style={{ marginLeft: -3 }}>({gridRowsData.length})</div>
                    <div
                      className="AuditSelectSampleDel"
                      style={{
                        marginLeft: -5,
                        marginTop: 5,
                        marginBottom: 5,
                      }}
                    >
                      <Button
                        icon="iconfont icon-del"
                        width={60}
                        height={32}
                        hint="删除选中项"
                        onClick={(e) => {
                          getDeleteGridSelectRows(
                            dataGridRef,
                            setConfirmDelete,
                            async (deleteRowKeys: any[]) => {
                              const newRowsData = gridRowsData.filter(
                                (item) => !deleteRowKeys.includes(item.rn),
                              );
                              setGridRowsData(newRowsData);
                            },
                          );
                        }}
                      />
                    </div>
                  </div>
                  <div style={{ marginLeft: 0, marginTop: 8 }}>
                    <DevGrid.RangeTap
                      className={` PaperDevSortableGrid devHeadersCenter `}
                      height={'100%'}
                      width="98vw"
                      id="devGriSampleSource"
                      dataSource={gridRowsData}
                      keyExpr="rn"
                      ref={dataGridRef}
                      columns={selectGridColumns} //不加这个,setSampleSourceDataColumns会导致这个报错
                      showBorders={true}
                      showRowLines={true}
                      showColumnLines={true}
                      allowColumnResizing={true}
                      loadPanel={{ enabled: true }}
                      isRemote={true}
                      columnMinWidth={30}
                      defaultFocusedRowIndex={0}
                      searchPanel={{ visible: false, width: 100 }}
                      headerFilter={{ texts: { ok: '确定' } }}
                      disableFirstHeaderSearch={true}
                      paging={{ enabled: false, pageSize: consts.maxSampleCount }}
                      //focusedRowEnabled={true} 这个属性不能加,会导致数组分页的totalCount不生效
                      remoteOperations={{ paging: false }} //加这个才能支持远程分页 本地过滤 20230507
                      renderAsync={true}
                      selection={{ mode: 'multiple' }}
                      editing={{ allowDeleting: true, confirmDelete: confirmDelete }}
                      focusedRowEnabled={true}
                      focusedRowIndex={focusedRowIndex}
                    />
                  </div>
                </div>
              )
            );
          }
          return (
            <>
              {sampleProjectOverallProps?.overallMode == OverallMode.select && (
                <LayoutD
                  columnSize={['60%', '40%']}
                  topSlot={topContainer()}
                  bottomSlot={bottomContainer()}
                />
              )}
              {sampleProjectOverallProps?.overallMode !== OverallMode.select && topContainer()}
            </>
          );
        }}
      </DevPopup.Logic>
    </>
  );
});
